package  com.worldtolearn.shoppingcart.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;

import com.worldtolearn.offer.bu.IOfferBu;
import com.worldtolearn.offer.bu.OfferBu;
import com.worldtolearn.order.bu.OrderBu;
import com.worldtolearn.order.entity.OrderLine;
import com.worldtolearn.user.bean.LoginMB;
import com.worldtolearn.user.entity.User;

@Controller
@Named
@ManagedBean
@SessionScoped
public class ShoppingCartMB implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(ShoppingCartMB.class);

	@ManagedProperty(value="loginMB")
	private LoginMB login;

	@Inject
	OrderBu orderBu;

	List<IOfferBu>  listCart ;

	private int qty = 1;
	private String label;
	private int offerId;
	private double costOffer;
	private int idOffer;
	private List<OrderLine> orderLineList;
	private Map<Integer,OrderLine> orderLineMap;
	private double total;

	@PostConstruct
	private void CreateMap(){
		System.out.println("Post constructing");

		orderLineMap = new Hashtable<Integer, OrderLine>();

	}

	public String saveAction() {

		//get all existing value but set "editable" to false 
		for (OrderLine order : orderLineList){
			if (order.getQty() == 0) {
				orderLineList.remove(order);
			}
			order.setEditable(false);
		}
		for (OrderLine order : orderLineList){
			System.out.println(order.toString());
		}
		
		return null;
	}


	public void action(ActionEvent event) {
		offerId =Integer.parseInt(event.getComponent().getAttributes().get("offerId").toString());
		costOffer =(Double) event.getComponent().getAttributes().get("costOffer");
		label =(String) event.getComponent().getAttributes().get("label");
		setCostOffer(costOffer);
		setLabel(label);

	}

	public String placeOrder() {

		//FacesContext fc =  FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance()
				.getExternalContext().getRequest();
		HttpSession session = ((HttpServletRequest) request).getSession(false);
		System.out.println("session : "+session);
		login = (session != null) ? (LoginMB) session.getAttribute("loginMB") : null;
		User user = (session != null) ? (User) session.getAttribute("user") : null;
		
		
		
		//trace

		@SuppressWarnings("unchecked")
		Enumeration<String> attrs = session.getAttributeNames();
		while (attrs.hasMoreElements()) {
			String type = (String)attrs.nextElement();
			System.out.println("check session type in shoppingcart : "+type);
		}
		if (login != null) {
			System.out.println("********************PlaceOrder()******if (login != null*************************");
			System.out.println("**login in shopping cart user name "+ login.getUser().getFirstName());
			System.out.println("**login in shopping cart user id  "+ login.getUser().getIdPerson());
			System.out.println("********************PlaceOrder()*******************************");
		}
		if (user != null) {
			System.out.println("********************PlaceOrder()******if (user != null*************************");
			System.out.println("user in shopping cart "+ user.getFirstName().toString());
			login.setUser(user);
			System.out.println("***********if user not null set login (user)********* ******************************"+ login.getUser().getFirstName());
			System.out.println("********************PlaceOrder()*******************************");
		}
		//fin trace
		
		
		
		
		
		if (login != null || user != null ) {

			if (login != null ) {
				orderBu.setOrder(getOrderLineList(), login.getUser());
			}else {
				login.setUser(user);
				orderBu.setOrder(getOrderLineList(), login.getUser());
			}
			System.out.println("debug order shoppingcart orderBu"
					+ " setOrder : order info, id : " 
					+ login.getUser().getIdPerson() + " -name : "+login.getUser().getFirstName() );
			orderBu.createOrderFromBean();
			
			orderLineMap = null;
			orderLineMap = new Hashtable<Integer, OrderLine>();
			orderLineList = null;
			orderLineList = new ArrayList<OrderLine>();
			System.out.println("isOrderOk : "+orderBu.isOrderOk());
			if (orderBu.isOrderOk()) {
				return "successOrder.jsf";
			}
			
		}
		return "login.jsf";
	}
	public void addCart() {
		//create a OrderLine object
		OrderLine orderLine = new OrderLine();
		orderLine.setIdOfferLine(getOfferId());
		orderLine.setLabel(getLabel());
		orderLine.setTotalCost(getCostOffer());
		orderLine.setOfferCost(getCostOffer());


		//add it in the Hashtable
		orderLineMap.put(orderLine.getIdOfferLine(), orderLine);
		Iterator<Map.Entry<Integer, OrderLine>> it = orderLineMap.entrySet().iterator();

		while (it.hasNext()) {
			Map.Entry<Integer, OrderLine> entry = it.next();
			System.out.println("boucle map qty : "+entry.getValue().getQty());

			// Remove entry if key is null or equals 0.
			if (entry.getKey() == null || entry.getKey() == 0) {
				it.remove();
			}
			if (entry.getValue().getQty() == 0) {
				System.out.println("suppression ligne :");
				it.remove();
			}
		}

		for (OrderLine li : getOrderLineList()) {
			System.out.println("li-------------"+li);
		}
	}
	public List<IOfferBu> getListCart() {
		return listCart;
	}

	public String viewCart() {
		//		return cart.isEmpty();
		if (orderLineList.isEmpty()) {
			return null;
		}
		System.out.println("viewCart");
		return "success";
	}

	public void setListCart(List< OfferBu> listCart) {
		//		this.listCart = (ArrayList<IProductBu>) listCart;
	}

	public int getQty() {
		return qty;
	}

	public void setQty(int qty) {
		this.qty = qty;
	}

	public int getOfferId() {
		return offerId;
	}

	public void setOfferId(int offerId) {
		this.offerId = offerId;
	}

	public double getCostOffer() {
		return costOffer;
	}

	public void setCostOffer(double costOffer2) {
		this.costOffer = costOffer2;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public List<OrderLine> getOrderLineList() {
		orderLineList = new ArrayList<OrderLine>(getOrderLineMap().values()); 

		return orderLineList;
	}

	public void setOrderLineList(List<OrderLine> orderLineList) {
		this.orderLineList = orderLineList;
	}


	public Map<Integer,OrderLine> getOrderLineMap() {
		return orderLineMap;
	}


	public void setOrderLineMap(Map<Integer,OrderLine> orderLineMap) {
		this.orderLineMap = orderLineMap;
	}


	public int getIdOffer() {
		return idOffer;
	}


	public void setIdOffer(int idOffer) {
		this.idOffer = idOffer;
	}

	public double getTotal() {
		//		List<OrderLine> totalListOrder = new ArrayList<OrderLine>();
		double tempToltal = 0;
		for (OrderLine ol : getOrderLineList()) {
			System.out.println("ligne de commande : " + ol.getLabel() + " qty "+ ol.getQty() + ol.getTotalCost() );
			tempToltal += ol.getTotalCost();
		}

		return tempToltal;
	}

	public void setTotal(double total) {
		this.total = total;
	}





}
